package map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.BiConsumer;
import java.util.Set;

import org.junit.Test;

public class HashMapDemo {
	@Test
	public void create() {
		Map<Integer,String> map = new HashMap<Integer,String>();
		// 添加? key,value是否可为空， key相同value是覆盖
		map.put(1, "one");
		map.put(2, "two");
		map.put(null, null);
		map.put(2, "twotwo");
		System.out.println(map);
	}
	
	@Test
	public void methods() {
		Map<Integer,String> map = new HashMap<Integer,String>();
		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		map.put(4, "four");
		map.put(5, "five");

		System.out.println("元素个数:" + map.size());
		System.out.println("根据key获取value:" + map.get(6));
		System.out.println("根据key获取value(没有就返回默认值):" + map.getOrDefault(6, "six"));
		System.out.println("判断是否有此key:" + map.containsKey(4));
		System.out.println("判断是否有此value:" + map.containsValue("two"));
		System.out.println("是否为空:" + map.isEmpty());
		// 替换
		map.replace(5, "fivefive");
		System.out.println(map);
		// 移除
		map.remove(5);
		System.out.println(map);
		// 清空
		map.clear();
		System.out.println(map);
	}
	
	@Test
	public void forEach() {
		Map<Integer,String> map = new HashMap<Integer,String>();
		map.put(1, "one");
		map.put(2, "two");
		map.put(3, "three");
		map.put(4, "four");
		map.put(5, "five");
		// 1.得到所有key
		Set<Integer> keySet = map.keySet();
		Iterator<Integer> it = keySet.iterator();
		while(it.hasNext()) {
			Integer key = it.next();
			System.out.println(key + ":" + map.get(key));
		}
		System.out.println("--------------------");
		
		// 2.开发推荐
		Set<Entry<Integer, String>> entrySet = map.entrySet();
		Iterator<Entry<Integer, String>> it2 = entrySet.iterator();
		while(it2.hasNext()) {
			Entry<Integer, String> entry = it2.next();
			System.out.println(entry.getKey() +":" + entry.getValue());
		}
		System.out.println("--------------------");
		
		// 3.forEach
		map.forEach(new BiConsumer<Integer, String>() {
			@Override
			public void accept(Integer t, String u) {
				System.out.println(t +":" + u);
			}
		});
	}
}














